package com.leetcode.tree.level_traversal;

import com.leetcode.basic.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author Dennis Li
 * @date 2020/6/16 20:38
 */
public class FindBottomLeftValue_513 {

    // 顺手把最大深度做了 -- LeetCode 面试题 55 - I
    public int maxDepth(TreeNode root) {
        return root == null ? 0 : 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }

    // 间接写法 -- 完美！
    public int findBottomLeftValue1(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        // 从右往左入队，那么最后出队的一定是最左边的
        while (!queue.isEmpty()) {
            root = queue.poll();
            if (root.right != null) queue.offer(root.right);
            if (root.left != null) queue.offer(root.left);
        }
        return root.val;
    }

    int res, d = 0;

    public int findBottomLeftValue2(TreeNode root) {
        dfs(root, 0);
        return res;
    }

    private void dfs(TreeNode root, int depth) {
        if (root == null) return;
        if (root.left == null && root.right == null) {
            if (d < depth) {
                res = root.val;
                d = depth;
            }
        }
        dfs(root.left, depth + 1);
        dfs(root.right, depth + 1);
    }


}
